package com.alpaak.common.exception;

import com.alpaak.common.enumtype.ErrorCodeEnum;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 模块说明: 统一异常处理Handler<br/>
 * 系统版本: v1.0  <br/>
 */
public class ExceptionHandler implements HandlerExceptionResolver {

	private final static Logger log = Logger.getLogger(ExceptionHandler.class);

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		ModelAndView mv = new ModelAndView();

		/*  使用response返回    */
		response.setStatus(HttpStatus.OK.value()); //设置状态码
		response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
		response.setCharacterEncoding("UTF-8"); //避免乱码  
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		//同源策略
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Headers", "Cache-Control");
		response.setContentType("text/json;charset=utf-8");

		StringBuilder sb = new StringBuilder();
		try {
			if (ex instanceof BusinessException) {
				BusinessException be = (BusinessException) ex;
				sb.append("{\"errCode\":\"" + be.getErrCode() + "\",\"errMsg\":\"" + be.getErrMsg() + "\",\"status\":0}");
				response.getWriter().write(sb.toString());
				log.info(sb.toString(), ex);
			} else {
				sb.append("{\"errCode\":\"" + ErrorCodeEnum.SYS_ERR.getErrCode() + "\",\"errMsg\":\"" + ErrorCodeEnum.SYS_ERR.getErrMsg() + ex.toString() + "\",\"status\":0}");
				response.getWriter().write(sb.toString());
				log.error(sb.toString(), ex);
			}
		} catch (IOException e) {
			log.error("系统内部异常:" + e.getMessage(), e);
		}
		return mv;
	}

}
